package cn.rwklyd.BookKeeping.util;

import com.aliyun.imageaudit20191230.Client;
import com.aliyun.imageaudit20191230.models.ScanImageRequest;
import com.aliyun.imageaudit20191230.models.ScanImageRequest.ScanImageRequestTask;
import com.aliyun.imageaudit20191230.models.ScanImageResponse;
import com.aliyun.tea.TeaException;
import com.aliyun.teaopenapi.models.Config;
import com.aliyun.teautil.models.RuntimeOptions;

import java.util.Arrays;

public class AliGreenImageScanUtil {

    private static final String ENDPOINT = "imageaudit.cn-shanghai.aliyuncs.com"; // 硬编码的 Endpoint
    private static final String ACCESS_KEY_ID = "LTAI5tFmzd1mPxB95bkRnrS2"; // 硬编码的 Access Key ID
    private static final String ACCESS_KEY_SECRET = "6Q7a3A2dqarnI1Q84uaMJgHBxJkbaO"; // 硬编码的 Access Key Secret

    private static Client client;

    static {
        try {
            Config config = new Config()
                    .setAccessKeyId(ACCESS_KEY_ID)
                    .setAccessKeySecret(ACCESS_KEY_SECRET);
            config.endpoint = ENDPOINT;
            client = new Client(config);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static ScanImageResponse auditImage(String imageUrl) throws Exception {
        ScanImageRequestTask task = new ScanImageRequestTask()
                .setImageURL(imageUrl);

        ScanImageRequest request = new ScanImageRequest()
                .setScene(Arrays.asList("porn", "terrorism"))
                .setTask(Arrays.asList(task));

        RuntimeOptions runtime = new RuntimeOptions();
        try {
            return client.scanImageWithOptions(request, runtime);
        } catch (TeaException error) {
            System.out.println("Error: " + error.getMessage());
            if (error.getData() != null) {
                System.out.println("Recommend: " + error.getData().get("Recommend"));
            }
            throw error;
        } catch (Exception error) {
            TeaException teaError = new TeaException(error.getMessage(), error);
            System.out.println("Error: " + teaError.getMessage());
            if (teaError.getData() != null) {
                System.out.println("Recommend: " + teaError.getData().get("Recommend"));
            }
            throw teaError;
        }
    }
}